package com.yhy.tradesystem.datasource;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;

import com.yhy.tradesystem.TradeDataPak;
import com.yhy.tradesystem.TradeSystemFilter;
import com.yhy.tradesystem.util.Log;

public class SimpleYahooFileDataSource extends BaseDataSource {

	ArrayList<TradeSystemFilter> outputFilter = new ArrayList<TradeSystemFilter>();
	
	private String stockName;
	private DataPeriod period;
	
	
	final static int DATE_INDEX=0;
	final static int OPEN_INDEX=1;
	final static int HIGH_INDEX=2;
	final static int LOW_INDEX=3;
	final static int CLOSE_INDEX=4;
	final static int VOL_INDEX=5;
	
	public final static String TAG="yhy";
	
	public ArrayList<Float> rawDataClose=new ArrayList<Float>();
	public ArrayList<Float> rawDataOpen=new ArrayList<Float>();
	public ArrayList<Float> rawDataHigh=new ArrayList<Float>();
	public ArrayList<Float> rawDataLow=new ArrayList<Float>();
	public ArrayList<Date> rawDataDate=new ArrayList<Date>();
	public ArrayList<Long> rawDataVol=new ArrayList<Long>();
	
	protected FileReader freader = null;
	protected BufferedReader bfreader = null;
	
	private int totalDataSizeInBytes;
	
	private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	
	private String rootDir = null;
	private int currentIndex = 0;
	
	public String getRootDir() {
		return rootDir;
	}

	public void setRootDir(String rootDir) {
		this.rootDir = rootDir;
	}

//	public boolean seekToRandomLinePosition(){
//		Random rand=new Random();
//		int skip = rand.nextInt( totalDataSizeInBytes/4 * 4/5);//不能skip太多，至少要留下若干条数据作为历史记录充满buffer，另外最好留下一年的数据
//		try {
//			bfreader.skip(skip);//use filereaer to skip will cause bfreader goes wrong!
//			String line = bfreader.readLine();
//			Log.d(TAG, String.format("skip %d in %d line %s", skip,totalDataSizeInBytes,line));
//			return true;
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return false;
//	}
//	
//	public boolean release(){
//		try {
//			bfreader.close();
//			freader.close();
//			return true;
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		return false;
//	}
	
	TradeDataPak outputPak = new TradeDataPak();
	boolean dataLoaded = false;
	
	@Override
	public void connectOutput(TradeSystemFilter filter) {
		outputFilter.add(filter);
	}

	@Override
	public void inputData(TradeDataPak data) {
		// TODO Auto-generated method stub

	}
	
	@Override
	public TradeDataPak outputData() {
		for(TradeSystemFilter filter:outputFilter){
			filter.inputData(outputPak);
		}
		return outputPak;
	}
	
	private void fillDataPak(){
		TradeDataPak.StockData data = new TradeDataPak.StockData(stockName,
				rawDataOpen.get(currentIndex), 
				rawDataClose.get(currentIndex),  
				rawDataHigh.get(currentIndex), 
				rawDataLow.get(currentIndex), 
				rawDataVol.get(currentIndex), 
				rawDataDate.get(currentIndex));
		outputPak = new TradeDataPak();
		outputPak.stockData = data;
	}
	

	@Override
	public boolean loadData(String stockName, DataPeriod period) {
		if(rootDir == null){
			Log.d("yhy","call setRootDir before loadData!");
			return false;
		}
		
		resetData();
		
		this.stockName = stockName;
		this.period = period;
		
		boolean ret=false;
		
		try {
			FileInputStream fis = new FileInputStream(rootDir+"/" +stockName+".csv");
			totalDataSizeInBytes = fis.available();
			fis.close();
			
			freader = new FileReader(rootDir+"/" +stockName+".csv");
			bfreader = new BufferedReader(freader);
			bfreader.readLine();// skip 1st line
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		long cnt=0;
		try {
			String line = bfreader.readLine();
			while(line!=null){
				String[] raw = line.split(",");
				if(raw.length!=7){
					Log.d("yhy", "loadData "+raw.length+" wrong data "+line);
					break;
				}
				rawDataClose.add(Float.parseFloat(raw[CLOSE_INDEX]));
				rawDataOpen.add(Float.parseFloat(raw[OPEN_INDEX]));
				rawDataHigh.add(Float.parseFloat(raw[HIGH_INDEX]));
				rawDataLow.add(Float.parseFloat(raw[LOW_INDEX]));
				rawDataVol.add(Long.parseLong(raw[VOL_INDEX]));
				try {
					rawDataDate.add(formatter.parse(raw[DATE_INDEX]));
				} catch (ParseException e) {
					e.printStackTrace();
					Log.d(TAG, "ParseException "+raw[DATE_INDEX]);
				}
				line = bfreader.readLine();
				cnt++;
				if(cnt % 100 ==0){
					Log.d("yhy", "loadData "+cnt);
				}
			}
			//yahoo的数据，最新的日期在第一行，最老的数据在最后一行，我们前进是从老到新
			currentIndex = rawDataClose.size() -1;
			bfreader.close();
			freader.close();
			dataLoaded = true;
			
			fillDataPak();
			outputData();
			Log.d("yhy", "loadData ok");
			ret = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}catch (IOException e) {
			e.printStackTrace();
		}
		return ret;
	}

	@Override
	public boolean seekToDate(Date date) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean goNextTick() {
		if(!dataLoaded){
			Log.d("yhy", "you haven't load data yet!");
			return false;
		}
		if(currentIndex>0){
			currentIndex --;
		}
		fillDataPak();
		outputData();
		return true;
	}

	@Override
	public String getName() {
		return SimpleYahooFileDataSource.class.getName();
	}

	@Override
	public void resetData() {
		rawDataOpen.clear();
		rawDataClose.clear();
		rawDataHigh.clear();
		rawDataLow.clear();
		rawDataDate.clear();
		rawDataVol.clear();
	}



}
